package net.ufrog.common.spring.interceptor;

import net.ufrog.common.Logger;
import net.ufrog.common.app.App;
import net.ufrog.common.cache.Caches;
import net.ufrog.common.utils.Codecs;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 属性拦截器
 *
 * @author ultrafrog, ufrog.net@gmail.com
 * @version 0.1, 2017-03-23
 * @since 0.1
 */
public class PropertiesInterceptor implements HandlerInterceptor {

    private static final String CACHE   = "prop";
    private static final String KEY     = Codecs.uuid();

    /** 属性管理器 */
    private PropertiesManager propertiesManager;

    @Override
    @SuppressWarnings("unchecked")
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        List<String> lKey = Caches.get(CACHE, List.class);
        if (lKey == null || !lKey.contains(KEY)) {
            Logger.info("properties cache rebuilding.");
            App.config(propertiesManager.load());

            lKey = (lKey == null) ? new ArrayList<>() : lKey;
            lKey.add(KEY);
            Caches.set(CACHE, lKey);
            Logger.info("properties rebuild completed.");
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {}

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {}

    /** 清空缓存 */
    public static void clear() {
        Caches.safeDelete(CACHE);
    }

    /**
     * 读取属性管理器
     *
     * @return 属性管理器
     */
    public PropertiesManager getPropertiesManager() {
        return propertiesManager;
    }

    /**
     * 设置属性管理器
     *
     * @param propertiesManager 属性管理器
     */
    public void setPropertiesManager(PropertiesManager propertiesManager) {
        this.propertiesManager = propertiesManager;
    }
}
